/// <reference path="../../../../../../../typings/angularjs/angular.d.ts"/>
define(["jquerySortable", "jsonpack", "jsonConverters"], function (jquerySortable, jsonpack, jsonConverters) {
	var app = angular.module("App.home");
	app.controller("projects.detail.layersCtrl", ["$scope", "$timeout", "$q", "$http", "curPrj", "Project", function ($scope, $timeout, $q, $http, curPrj, Project) {
		$scope.fileChanged = function (elem) {
			$scope.$apply(function () {
				$scope.files = elem.files;
				$scope.valid = valid($scope.files);
				$timeout(function () {
					$(".sortable").sortable().bind("sortupdate", function () {});
				}, 500);
			});
		};
		$scope.upload = function () {
			if ($scope.status === "uploading")
				return;
			$scope.status = "uploading";
			var list = $(".sortable").children();
			var sorted = [];
			for (var i = list.length - 1; i >= 0; i--) {
				for (var j = 0; j < $scope.files.length; j++) {
					if ($scope.files[j].name === $(list[i]).text()) {
						$scope.files[j].className = "pending";
						sorted.push($scope.files[j]);
						break;
					}
				}
			}
			var layers = [];
			sorted.reduce(function (previous, current) {
				return previous.then(function () {
					var deferred = $q.defer();
					var reader = new FileReader();
					var _current = current;
					var errorHandler = function (ev) {
						deferred.reject(ev);	
					};
					var loadHandler = function (ev) {
						try {
							layers.push({
								data: jsonpack.pack(jsonConverters.esriConverter().toGeoJson(JSON.parse(reader.result))),
								name: _current.name.substr(0, _current.name.length - 5)
							});
							_current.className = "done";
							deferred.resolve();
						} catch (error) {
							_current.className = "error";
							deferred.reject(error);
						}
					};
					current.className = "progress";
					reader.addEventListener("error", errorHandler);
					reader.addEventListener("load", loadHandler);
					reader.readAsText(current);
					return deferred.promise;
				});
			}, $q.when()).then(function () {
				curPrj.postLayers(JSON.stringify(layers));
			}).then(function () {
				$scope.status = "success";
			}, function (reason) {
				$scope.status = "failure";
				console.log(reason);
			});
		};
		$scope.files = [];
		$scope.status = null;
		$scope.valid = false;
		var valid = function (files) { // 检查是否含有 Pit / RingNumber / Annotation 图层
			var count = 0;
			for (var i = 0; i < files.length; i++) {
				var name = files[i].name.toLowerCase();
				if (name === "pit.json" || name === "ringnumber.json" || name === "annotation.json")
					count++;
			}
			return count === 3;
		};
	}]);
});